<?php
namespace app\weixin\controller;
use think\Config;
use think\Session;
use app\weixin\controller\BaseController;
use app\common\model\Options;
use app\weixin\model\TPWechat;
use app\weixin\model\WeixinApp;
use app\weixin\model\WeixinUser;
class IndexController extends BaseController{
  public function _initialize($skip_action = []){
    $skip_action = [];
    parent::_initialize($skip_action);

    $state = $this->request->param("state");
    if(empty($state)){
      $this->appid = $this->request->param("appid");
    }else{
      $this->appid = $state;
    }

    if(empty($this->appid)){
      $current_weixin_app = session_current_weixin_app();
      if($current_weixin_app){
        $this->appid = $current_weixin_app["id"];
      }
    }
  }

  //验证授权信息
  public function valid(){
    $chat = new TPWechat($this->appid);
    $is_valid = $chat->valid();

    $type = $weObj->getRev()->getRevType();
    if($type){
      switch($type){
      case $chat::MSGTYPE_EVENT:
        $event_name = $chat->event;
        $data = array();
        $map = array("openid" => $chat->getRevFrom());
        switch($chat->getRevEvent()){
        case "subscribe":
          $data = array("subscribe" => 1, "subscribed_at" => 1000);
          break;
        case "unsubscribe":
          $data = array("subscribe" => 0, "subscribed_at" => NULL);
          break;
        }
        if($map && $data){
          $modelUser = D("WeixinUser");
          $modelUser->where($map)->create($data, 2);
          $modelUser->save();
        }
        break;
      }
    }else{
      $is_valid;
    }
  }

  // 获取用户信息授权发起页面
  public function auth(){
    if(is_numeric($this->appid)){
      $field_name = "id";
    }else{
      $field_name = "appid";
    }
    $AppModel = new WeixinApp();
    $weixin_app = $AppModel->where($field_name, $this->appid)->find();
    if(empty($weixin_app)){
      echo("请求参数错误, appid: {$this->appid}");
      exit();
    }

    $OptionsModel = new Options();
    $site_host = $OptionsModel->getSiteHost();
    // 是否是从test server跳转过来授权的
    $environment = Config::get("environment");
    $production_host = Config::get("production_host");
    if(empty($production_host)){
      $production_host = $site_host;
    }

    switch($environment){
    case "development":
      // 非开发环境
      $openid = null;
      $app_lists = Config::get("weixin_apps");
      foreach ($app_lists as $app) {
        if($app["appid"] == $weixin_app["appid"]){
          $openid = $app["openid"];
          break;
        }
      }
      if(empty($openid)){
        echo("no test user");
      }else{
        change_current_weixin_user($openid);
        $oauth_back_url = Session::pull("oauth_back_url");
        if(empty($oauth_back_url)){
          $oauth_back_url = $weixin_app["auth_callback"];
        }
        if(empty($oauth_back_url)){
          $oauth_back_url = "/";
        }
        $this->redirect($oauth_back_url);
      }
      break;
    default:
      // production
      $chat = new TPWechat($weixin_app["appid"]);
      $url = $production_host.url("weixin/Index/callback", array("from_env" => $environment));
      $redirect_url = $chat->getOauthRedirect($url, $weixin_app["appid"], $weixin_app["auth_scope"]);
      $this->redirect($redirect_url);
      break;
    }
  }

  //微信授权回调方法
  public function callback(){
    $AppModel = new WeixinApp();
    $UserModel = new WeixinUser();
    $weixin_app = $AppModel->where("appid", $this->appid)->find();
    if(empty($weixin_app)){
      echo("回调参数错误");
    }else{
      // 是否是从test server跳转过来授权的
      $from_env = $this->request->param("from_env");
      if($from_env == "test"){
        $query_param = [];
        $query_param["code"] = $this->request->param("code");
        $query_param["state"] = $this->request->param("state");
        // 是从测试服过来的授权请求，回到测试服去
        $action_path = url("weixin/index/callback");
        $query_str = http_build_query($query_param);
        $test_host = Config::get("test_host");
        // 跳转到测试站的链接不能使用伪静态
        $oauth_back_url = $test_host.$action_path."?".$query_str;
      }else{
        $token = $UserModel->authCallback($this->appid);
        change_current_weixin_user($token["openid"]);
        $oauth_back_url = Session::pull("oauth_back_url");
        if(empty($oauth_back_url)){
          $oauth_back_url = $weixin_app["auth_callback"];
        }
        if(empty($oauth_back_url)){
          $oauth_back_url = "/";
        }
      }
      $this->redirect($oauth_back_url);
    }
  }

  public function access_token(){
    $chat = new TPWechat($this->appid);
    $access_token = $chat->checkAuth();
    if($access_token){
      $res = ["access_token" => $access_token];
    }else{
      $res = [];
    }
    return json($res);
  }

  public function js_ticket(){
    $chat = new TPWechat($this->appid);
    $js_ticket = $chat->getJsTicket();
    if($js_ticket){
      $res = ["js_ticket" => $js_ticket];
    }else{
      $res = [];
    }
    return json($res);
  }
}